package com.example.springbootdemo.processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {
  @Override
  public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< happen before destroy,as @Destroy");
    }
  }

  @Override
  public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< happen before create instance,this object will replace last object");
    }
    return null;
  }

  @Override
  public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< happen after create instance,it will skip autoWried step when return false");
    }
    return true;
  }

  @Override
  public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< execute autowried step,as @Autowried,@Value,@Resource");
    }
    return pvs;
  }

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< happen before initial instance, last bean will be replaced this return object,as @PostConstruct,@ConfigurationProperties");
    }
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if ("lifeCycleBean".equals(beanName)) {
      log.debug("<<<<<<<<< happen after initial instance, last bean will be replaced this return object,as proxy");
    }
    return bean;
  }
}
